package com.xyhuo.leetcode.december;

import java.util.*;

/**
 * 合并区间
 * https://leetcode.cn/problems/merge-intervals/
 *
 * @time 2023/12/22
 */
public class Merge {

    static class Pair {
        int left;
        int right;

        Pair(int left, int right) {
            this.left = left;
            this.right = right;
        }

        /**
         * 判断是否重叠
         *
         * @param left
         * @param right
         * @return
         */
        boolean overlap(int left, int right) {
            if (left <= this.right && left >= this.left) {
                return true;
            }

            if (right <= this.right && right >= this.left) {
                return true;
            }
            return false;
        }

        void newPair(int left, int right) {
            this.left = Math.min(this.left, left);
            this.right = Math.max(this.right, right);
        }

    }

    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        Deque<Pair> deque = new ArrayDeque<>();
        deque.add(new Pair(intervals[0][0], intervals[0][1]));
        for (int i = 1; i < intervals.length; i++) {
            Pair last = deque.getLast();
            if (last.overlap(intervals[i][0], intervals[i][1])) {
                last.newPair(intervals[i][0], intervals[i][1]);
            } else {
                deque.addLast(new Pair(intervals[i][0], intervals[i][1]));
            }
        }
        int[][] ans = new int[deque.size()][2];
        int index = 0;
        while (!deque.isEmpty()) {
            Pair pair = deque.removeFirst();
            ans[index][0] = pair.left;
            ans[index][1] = pair.right;
            index++;
        }
        return ans;
    }
}
